import Modals from '@/components/modals/Modals';
import { Flex, Spin } from 'antd';
import { Search, Empty } from '@/components/eai-design';
import { useEffect, useState, useRef } from 'react';
import '@/components/work-modal/work.scss'
import { GetWorkBenhList, AppsData } from '@/common';
import { formatDataNoTime } from '@/utils/time';
import mcpService from '@/api/services/mcpService';
import bgLayer from '@/assets/images/background/bg-layer.png';
import AvatarDisplay from '@/components/work-modal/components/AvatarDisplay';
import GradientBox from '@/components/GradientBox';

interface AppItem {
  id: string;
  name: string;
  description: string;
  icon?: React.ReactNode;
}

interface AppSelectProps {
  open: boolean;
  title?: any;
  isMultiSelect?: number; //是否多选  0 模板 1单选 2多选
  selectAppList?: AppsData[]; // 选中情况下传入的选中数据
  searchText?: string;
  onOk?: () => void;
  onCancel?: () => void;
}

interface pageType {
  page: number;
  pageSize: number;
  searchText: string;
  needPagination: boolean;
  appType?: string;
}


const AppSelect: React.FC<AppSelectProps> = ({
  open,
  title,
  searchText = '',
  isMultiSelect = 0,
  selectAppList = [],
  onOk,
  onCancel,
}) => {
  const workAllRef = useRef<HTMLDivElement>(null);
  const [isNoData, setIsNoData] = useState<boolean>(true);
  const [selectedItems, setSelectedItems] = useState<GetWorkBenhList[]>([]);
  const [dataList, setDataList] = useState<GetWorkBenhList[]>([]);
  const [activeIndex, setActiveIndex] = useState<number>(-1);
  const [isHaveData, setIsHaveData] = useState<boolean>(true);
  const [total, setTotal] = useState<number>(0);
  const [isInitialized, setIsInitialized] = useState(false);
  const [flag, setflag] = useState<boolean>(false); // 用于防止多次触发
  const [defaultPage, setDefaultPage] = useState<pageType>({
    page: 1,
    pageSize: 20,
    searchText,
    needPagination: true,
    appType: 'workflow',
  });

  const baseStyle: React.CSSProperties = {
    height: 238,
    borderRadius: 12,
    background: '#FEFFFF',
    cursor: 'pointer',
    position: 'relative',
    flexShrink: 0,
  };

  useEffect(() => {
    if (open) {
      // 打开弹窗时重置状态
      setSelectedItems([]);
      setDataList([]);
      setTotal(0);
      setIsInitialized(false);
      setflag(false);
      setDefaultPage((prev) => ({ ...prev, searchText: '', page: 1, offset: 0 }));
      if (selectAppList.length > 0) {
        setSelectedItems(selectAppList);
      }
    }
  }, [open]);

  const changeOk = () => {
    if (selectedItems && onOk) {
      onOk(selectedItems);
    } else {
      onCancel && onCancel();
    }
  };

  // 获取数据并处理预选
  const getPublic = async () => {
    try {
      const res = await mcpService.getApproved(defaultPage);
      setIsNoData(true);
      const newData = [...dataList, ...res.list];
      const datas = newData.map((item) => {
        return {
          ...item,
          checked:
            selectedItems.some((selectedItem) => selectedItem.appId === item.app_id) &&
            !selectAppList.some((app) => app.appId === item.app_id),
        };
      });
      setDataList(datas);
      setIsHaveData(newData.length > 0);
      setflag(false);
      setTotal(res.total);

      if (!isInitialized) setIsInitialized(true);
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    getPublic();
  }, [defaultPage]);

  const changeSearchValue = (e: any) => {
    setDefaultPage((prev) => ({
      ...prev,
      searchText: e.target.value,
      page: 1,
    }));
    setDataList([]);
  };

  function mouseEvent(e: number) {
    return () => {
      setActiveIndex(e);
    };
  }

  function mouseLeave() {
    return () => {
      setActiveIndex(-1);
    };
  }

  // 下拉触底操作
  const Scroll = () => {
    if (workAllRef.current) {
      const height1 = workAllRef.current.clientHeight; // 可以得到我们设置的高度 (不包括滚动的高度)
      const height2 = workAllRef.current.scrollTop; // 当滚动时被卷去的高度
      const height3 = workAllRef.current.scrollHeight; // 全部的高度 包括滚动的高度
      if (height1 + height2 + 20 > height3 && !flag) {
        // 当距离底部20 则会触发
        // 加了flag 是为了防止反复触发
        setflag(true);
        // 这里进行请求
        if (dataList.length < total) {
          setDefaultPage((prev) => ({
            ...prev,
            page: defaultPage.page + 1,
            offset: -1,
          }));
        }
      }
    }
  };

  const confirmOk = (obj: GetWorkBenhList) => {
    const isLocked = isMultiSelect === 2 && selectAppList.some((app) => app.appId === obj.app_id);

    if (isLocked) {
      return;
    }

    if (isMultiSelect === 0) return;

    setDataList((prevData) => {
      return prevData.map((item) => {
        if (item.app_id !== obj.app_id) {
          if (isMultiSelect === 1) {
            return { ...item, checked: false };
          }
          return item;
        }
        return { ...item, checked: !item.checked };
      });
    });

    setSelectedItems((prev) => {
      if (isMultiSelect === 1) {
        return obj.checked ? [] : [obj];
      }

      const exists = prev.some((item) => item.appId === obj.app_id);
      if (exists) {
        return prev.filter((item) => item.appId !== obj.app_id);
      }

      const newObj = {
        appId: obj.app_id,
        appName: obj.name,
        description: obj.description,
        toolName: obj.name,
      };
      return [...prev, newObj];
    });
  };

  return (
    <Modals
      width={960}
      title={title}
      open={open}
      onOk={changeOk}
      onCancel={onCancel}
      okText={`添加${selectedItems.length}个应用`}
      className="modals-mode"
      destroyOnHidden
    >
      <div className="flex justify-start">
        <Search
          value={defaultPage.searchText}
          onChange={changeSearchValue}
          className="mb-[15px] !rounded-md"
          style={{
            height: '32px',
            width: '200px',
          }}
          placeholder="请输入内容"
        />
      </div>

      <div>
        <div
          ref={workAllRef}
          onScroll={Scroll}
          className="flex h-[500px] min-w-[290px] flex-1 flex-col overflow-auto px-2"
        >
          {!isNoData ? (
            <Flex align="center" gap="middle" className="flex h-full items-center justify-center">
              <Spin size="large" />
            </Flex>
          ) : (
            <>
              <Flex className="grid-app">
                {Array.from(dataList).map((item: any, i) => (
                  <GradientBox
                    key={`${item.app_id}-${i}`}
                    active={item.checked}
                    style={{ ...baseStyle }}
                    className={`boxs bg-[#ffffff] !shadow-none ${isMultiSelect === 2 &&
                      selectAppList.some((app) => app.appId === item.app_id)
                      ? '!cursor-no-drop !border-none !shadow-none'
                      : 'box-hover'
                      }`}
                    onMouseEnter={mouseEvent(i)}
                    onMouseLeave={mouseLeave()}
                    onClick={() => {
                      confirmOk(item);
                    }}
                  >
                    {isMultiSelect === 2 &&
                      selectAppList.some((app) => app.appId === item.app_id) && (
                        <div className="absolute right-0 top-0 z-10 rounded-bl-2xl rounded-tr-[10px] bg-functional-green px-3 py-1 text-center text-xs text-grays">
                          已添加
                        </div>
                      )}
                    <div
                      style={{
                        background: `url(${bgLayer}) no-repeat #FFF center top`,
                        backgroundSize: '50% 100%',
                      }}
                      className="absolute left-0 top-0 flex h-[116px] w-full justify-center rounded-xl pt-4"
                    >
                      <div>
                        <AvatarDisplay
                          src={item.app_logo}
                          className="h-[56px] w-[56px]"
                          size={50} />
                      </div>
                    </div>
                    <div
                      className="relative z-10  mt-[66px] px-5 pt-5 backdrop-blur-sm"
                      style={{
                        borderTop: '1px solid transparent',
                        backgroundImage:
                          'linear-gradient(270deg, rgba(255, 255, 255, 0.04) 0%, #FFFFFF 50%, rgba(255, 255, 255, 0.04) 100%), linear-gradient(270deg, rgba(0, 0, 0, 0.04) 0%, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0.04) 100%)',
                        backgroundOrigin: 'border-box',
                        backgroundClip: 'border-box',
                        backgroundSize: '100% 1px, 100% 1px',
                        backgroundPosition: 'top left',
                        backgroundRepeat: 'no-repeat',
                        width: '99%',
                      }}
                    >
                      <div className="w-[95%] min-w-[50px] truncate text-base font-bold">
                        {item.name}
                      </div>
                      <div className=" mb-4 mt-2 flex items-center justify-between text-xs text-[#074B79]">
                        <div
                          className=" h-[18px] rounded-small px-[6px] text-xs leading-[18px]"
                          style={
                            { background: '#E3C7FD', color: '#280976' }
                          }
                        >
                          工作流
                        </div>
                        <div className="flex h-5 w-2/4 justify-end text-xs">
                          <span className="mt-[1px] whitespace-nowrap text-[#C9CDD4]">By</span>
                          <div className="ml-2 flex max-w-[12em] items-center text-text-3">
                            <div className="max-w-[5em] truncate">
                              {item?.createUser?.groupName}
                            </div>
                            <div className=" whitespace-nowrap">/</div>
                            <div className="max-w-[5em] truncate">
                              {item?.createUser?.userName}
                            </div>
                          </div>
                        </div>
                      </div>
                      <div className=" line-clamp-2 h-9 overflow-hidden  text-ellipsis  text-sm text-[#4E5969]">
                        {item.description}
                      </div>
                    </div>
                    <div className=" flex h-10 items-center justify-between rounded-bl-xl rounded-br-xl bg-[#FEFFFF] px-5 ">
                      <div className=" text-xs text-text-3">
                        {formatDataNoTime(item.create_time)}
                        <span className="ml-1">更新</span>
                      </div>
                    </div>
                  </GradientBox>
                ))}
              </Flex>
              {dataList.length <= 0 && <Empty iconSize={80} textClassName="text-sm" />}
            </>
          )}
        </div>
      </div>
    </Modals>
  );
};

export default AppSelect;
